package com.dc.di.ftpserver.command;

import java.io.IOException;

import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EXISTDIR extends AbstractCommand{
	private final Logger LOG = LoggerFactory.getLogger(EXISTDIR.class);
	@Override
	public void execute(FtpIoSession session, FtpServerContext context,
			FtpRequest request) throws IOException, FtpException {
		// reset state
        session.resetState();

        // argument check
        String fileName = request.getArgument();
        if (fileName == null) {
        	session
	        .write(new DefaultFtpReply(FtpReply.REPLY_504_COMMAND_NOT_IMPLEMENTED_FOR_THAT_PARAMETER, "Argument is null"));
	        return;
        }
        FtpFile file = null;
        try {
            file = session.getFileSystemView().getFile(fileName);
        } catch (Exception ex) {
            LOG.debug("Exception getting file object", ex);
        }
        if (file == null) {
        	session
	        .write(new DefaultFtpReply(FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "file does not exist"));
            return;
        }
        fileName = file.getAbsolutePath();
        if (!file.doesExist()) {
        	session
	        .write(new DefaultFtpReply(FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "file does not exist"));
            return;
        } else if (file.isFile()) {
        	session
	        .write(new DefaultFtpReply(FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "file is a file"));
        }else if (file.isDirectory()) {
        	session
	        .write(new DefaultFtpReply(FtpReply.REPLY_200_COMMAND_OKAY, "file exist"));
        }
	}
	
	public static String getCommmand(){
		return "EXISTDIR";
	}
}
